<?php
/**
 * @Name: RoleLogic.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace App\Http\Logic\Rbac;

use App\Http\Logic\BaseLogic;
use App\Http\Model\Rbac\NodeModel;
use App\Http\Model\Rbac\RoleModel;
use App\Http\Model\Rbac\RoleNodeModel;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class RoleLogic extends BaseLogic
{

    /**
     * @Desc 添加
     * @return int
     * @author yashuai<1762910894@qq.com>
     */
    public function create()
    {
        $data = [
            'RoleName'   => $this->params['RoleName'],
            'RoleDesc'   => $this->params['RoleDesc'],
            'RoleStatus' => _array_field($this->params, 'RoleStatus', ConstCode::BASIC_STATUS_NORMAL),
        ];
        return RoleModel::newInsert($data);
    }

    /**
     * @Desc 更新
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function update()
    {
        $info = RoleModel::getInfo($this->params['RoleID'], 'RoleID');
        if (empty($info)) {
            _throw('', 106001);
        }
        $data = [
            'RoleName'   => $this->params['RoleName'],
            'RoleDesc'   => $this->params['RoleDesc'],
            'RoleStatus' => _array_field($this->params, 'RoleStatus', ConstCode::BASIC_STATUS_NORMAL),
        ];
        return RoleModel::query()->where(['RoleId' => $this->params['RoleID']])->update($data);
    }

    /**
     * @Desc 修改状态
     * @return int
     * @author yashuai<1762910894@qq.com>
     */
    public function status()
    {
        return RoleModel::query()->where(['RoleId' => $this->params['ID']])->update([
            'UpdateTime' => time(),
            'RoleStatus' => $this->params['Status']
        ]);
    }

    /**
     * @Desc 角色设置菜单节点
     * @tips 需要事务
     * @return boolean
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function node()
    {
        $info = RoleModel::getInfo($this->params['RoleID'], 'RoleID');
        if (empty($info) || $info['RoleStatus'] != ConstCode::BASIC_STATUS_NORMAL) {
            _throw('', 106001);
        }
        $node = NodeModel::query()->whereIn('NodeID', $this->params['NodeID'])->pluck('NodeID')->toArray();
        if (empty($node)) {
            _throw('菜单节点不存在', 106001);
        }
        $data = [];
        foreach ($node as $nodeID) {
            $data[] = [
                'RoleID' => $this->params['RoleID'],
                'NodeID' => $nodeID,
            ];
        }
        RoleNodeModel::query()->where(['RoleID' => $this->params['RoleID']])->delete();
        RoleNodeModel::newInsert($data);
        return true;
    }


}
